package com.yang.servlet;

import com.google.gson.Gson;
import com.yang.pojo.Category;
import com.yang.pojo.ResultVO;
import com.yang.service.CategoryService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.ArrayList;

@WebServlet("/CategoryListAjaxServlet")
public class CategoryListAjaxServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        CategoryService categoryService = new CategoryService();
        try {
            ArrayList<Category> categorys = categoryService.findCategory();
            //2、响应ajax请求，将category转换成json格式响应给页面的ajax请求
            ResultVO vo = categorys != null ? new ResultVO(1000,"success",categorys) :
                    new ResultVO(1001,"fail");
            String jsonStr = new Gson().toJson(vo);
            response.setContentType("application/json;charset=utf-8");
            PrintWriter writer = response.getWriter();
            writer.println(jsonStr);
            writer.flush();
            writer.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
